package task_process

import (
	"time"

	"github.com/hibiken/asynq"
)

func getClient(tag string) *asynq.Client {
	redisOpt := GetRedisCon()
	c := asynq.NewClient(*redisOpt)
	if optMap.Contains(tag) {
		topt := optMap.Get(tag).(*Taskoption)
		delay := time.Duration(int64((topt.TimeOut) * 1000000000))
		c.SetDefaultOptions(tag, asynq.MaxRetry(int(topt.RetryCount)), asynq.Timeout(delay))
	}
	return c
}

func AddTaskToQueue(tag string, payload map[string]interface{}, delaySeconds int64) error {
	c := getClient(tag)
	defer c.Close()
	t := asynq.NewTask(tag, payload)
	if delaySeconds == 0 {
		_, err := c.Enqueue(t)
		return err
	} else {
		delay := time.Duration(int64((delaySeconds) * 1000000000))
		optDelay := asynq.ProcessIn(delay)
		_, err := c.Enqueue(t, optDelay)
		return err
	}
}

func AddTimescheduledTask(tag string, payload map[string]interface{}, exeAt time.Time) error {
	c := getClient(tag)
	defer c.Close()

	optAt := asynq.ProcessAt(exeAt)

	t := asynq.NewTask(tag, payload)
	_, err := c.Enqueue(t, optAt)
	return err
}

// for example
func AddImageTask() {

	// err := AddTaskToQueue(EmailDelivery, g.Map{"user_id": 42, "template_id": "some:template:id"}, 0)
	// if err != nil {
	// 	log.Fatal("could not enqueue task: %v", err)
	// }

	// err = AddTaskToQueue(ImageProcessing, g.Map{"src": "some/blobstore/url", "dst": " dst"}, 20)
	// if err != nil {
	// 	log.Fatal("could not enqueue task: %v", err)
	// }

	// err = AddTaskToQueue(OtherProcessing, g.Map{"src": "some/blobstore/url", "dst": " dst"}, 20)
	// if err != nil {
	// 	log.Fatal("could not enqueue task: %v", err)
	// }

	// err = AddTimescheduledTask(EmailDelivery, g.Map{"user_id": 45, "template_id": "some:template:id"}, time.Now())
	// if err != nil {
	// 	log.Fatal("could not enqueue task: %v", err)
	// }

}
